/*
 * @Author: lihaonan
 * @Date: 2023-08-22 14:51:43
 * @LastEditors: 毕晨曦
 * @LastEditTime: 2024-12-11 21:52:52
 * @Description: 公共请求封装
 */
import Fly from "flyio/dist/npm/wx.js";
import { tansParams } from "./index";
import type { FlyRequestConfig, FlyResponse, FlyError } from "flyio";
/**
 * @link https://wendux.github.io/dist/#/doc/flyio/readme
 */
const fly = new Fly();

// 请求超时时间
fly.config.timeout = 10000;
// 公共请求头
fly.config.baseURL = import.meta.env.VITE_BASE_URL;

//添加请求拦截器
fly.interceptors.request.use((request: FlyRequestConfig) => {
  const token = uni.getStorageSync("token");
  request.headers["Authorization"] = token;

  //给所有请求添加自定义header
  //request.headers["X-Tag"]="flyio";
  if (request.method === "GET" && request.body) {
    let url = request.url + "?" + tansParams(request.body);
    url = url.slice(0, -1);
    request.body = {};
    request.url = url;
  }
  //给请求添加自定义header
  if (request.method !== "GET" && request.body && request.body.useContentType) {
    request.headers["Content-Type"] = request.body.useContentType;
  }
  return request;
});

fly.interceptors.response.use(
  (response: FlyResponse) => {
    // 登陆过期
    if (response.data.code == 401) {
      // uni.showToast({
      //   title: "请登陆体验完整功能",
      //   duration: 1600,
      //   icon: "error",
      // });
      // setTimeout(() => {
      //   uni.navigateTo({
      //     url: "/pages/login/index",
      //   });
      // }, 1600);

      return response.data;
    }
    return response.data;
  },
  (err: FlyError) => {
    // 接口错误提示
    uni.showToast({
      title: err.message,
      duration: 1600,
      icon: "error",
    });
    return err;
  }
);

export default fly;
